<?php


namespace app\common\library;


use common;

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

class AMapModel {

    var $_key = 'fa1fd1bbf28e2265ae26216c6a9f68b8';//'89605db587de0c034a986a5ddcadd268';//'18c8c468879aeb57aa7dab23ce561e01';

    function grasproad($track) {
        $body = [];
        if (count($track) > 500) {
            $rate = count($track) / 500;
            for ($i = 0, $k = 0; $i < count($track), $k < 500; $i++) {
                $ii = $i / $rate;
                if ($ii >= $k) {

                    $body[] = [
                        'x' => round($track[$i][0], 6),
                        'y' => round($track[$i][1], 6),
                        'ag' => $track[$i][4],
                        'tm' => strtotime($track[$i][2]),
                        'sp' => $track[$i][3],
                    ];
                    $k++;
                }
            }
        } else {
            for ($i = 0; $i < count($track); $i++) {
                $body[] = [
                    'x' => round($track[$i][0], 6),
                    'y' => round($track[$i][1], 6),
                    'ag' => $track[$i][4],
                    'tm' => strtotime($track[$i][2]),
                    'sp' => $track[$i][3],
                ];
            }
        }

        $url = "https://restapi.amap.com/v4/grasproad/driving?key={$this->_key}";
        $ret = common::curlpostjson($url, $body);

        if ($ret['errcode'] == 0 && !empty($ret['data']['points'])) {
            $l = [];
            foreach ($ret['data']['points'] as $item) {
                $l[] = [$item['x'], $item['y']];
            }
            return $l;
        }
        return null;
    }

    function map_c_2_a($coordinate) {
        $url = "https://restapi.amap.com/v3/geocode/regeo?key={$this->_key}&location={$coordinate[0]},{$coordinate[1]}&poitype=&radius=10&extensions=base&batch=false&roadlevel=0";

        $content = common::curlget($url, null);
        if (empty($content))
            return false;


        $j = json_decode($content, true);
        if (empty($j)) {
            return $j;
        }

        if ($j['status'] != '1') {
            return false;
        }

        if (isset($j['regeocode']) && isset($j['regeocode']['formatted_address'])) {
            return $j['regeocode']['formatted_address'];
        }
    }

}
